<template>
  <div class="pageOut">
    <div class="pageIn">
      <div class="flexRow">
        <div>
          <BackButton pages="/LockerList" />
          <span class="textBlod">格口管理</span>
          <span
            >设备编号：<span style="color: #666666">{{
              lockerRow.deviceCode
            }}</span></span
          >
          <span
            >设备名称：<span style="color: #666666">{{
              lockerRow.deviceName
            }}</span></span
          >
        </div>
        <!-- <span>所属商户：{{ lockerRow.merchantName }}</span> -->
        <el-button
          icon="el-icon-plus"
          type="primary"
          size="small"
          @click="handleAdd"
          v-show="permission.goodsSet"
          >批量设置商品</el-button
        >
      </div>

      <el-table
        border
        ref="table"
        :height="height - 130"
        :data="tableData"
        :header-cell-style="{ background: '#FAFAFA', color: '#606266' }"
        v-loading="loading"
        element-loading-background="rgba(255, 255, 255, 0.5)"
        style="width: 100%"
      >
        <el-table-column
          prop="gridCode"
          width="100"
          label="格口号"
        ></el-table-column>
        <el-table-column prop="usageName" label="使用状态"> </el-table-column>
        <el-table-column
          prop="goodsName"
          :show-overflow-tooltip="tooltip"
          label="所售商品"
        ></el-table-column>
        <el-table-column prop="stockName" label="库存"></el-table-column>
        <el-table-column :show-overflow-tooltip="tooltip" label="销售记录">
          <template slot-scope="scope">
            <el-link type="primary" @click="getorderList(scope.row.id)"
              >查看</el-link
            >
          </template>
        </el-table-column>

        <el-table-column
          fixed="right"
          width="450px"
          label="操作"
          align="center"
        >
          <template slot-scope="scope">
            <el-button type="primary" size="mini">开柜</el-button>
            <el-button
              type="primary"
              size="mini"
              @click="inventoryEdit(scope.row)"
              v-show="permission.add"
              >库存编辑</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="handleEdit(scope.row, 'one')"
              v-show="permission.edit"
              >商品编辑</el-button
            >
            <!-- <el-button
              type="primary"
              size="mini"
              @click="handleEdit(scope.row)"
              v-show="permission.edit"
              >编辑</el-button
            > -->
            <el-button
              :type="scope.row.usageStatus == 2 ? 'primary' : 'danger'"
              size="mini"
              @click="handleDel(scope.row)"
              v-show="permission.gridDel"
              >{{ scope.row.usageStatus == 2 ? "启用" : "禁用" }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 商家添加和商家编辑 -->
      <el-dialog
        width="50% "
        :visible.sync="visible"
        @close="onCancel"
        custom-class="custom_drawer"
      >
        <div class="flexRow" style="width: 80%">
          <span>设备编号：{{ lockerRow.deviceCode }}</span>
          <span>设备名字：{{ lockerRow.deviceName }}</span>
          <span>所属商户：{{ lockerRow.merchantName }}</span>
          <span>格口号：{{ currentRow.gridCode }}</span>
        </div>
        <div class="contentBox">
          <div v-if="Number(currentRow.goodsId) == 0"></div>
          <div v-if="Number(currentRow.goodsId) != 0">
            <div>当前商品</div>
            <div class="goodsBox">
              <img
                width="120px"
                height="150px"
                :src="currentRow.mainPicture"
                alt=""
              />
              <div class="sloganaBox">
                <div class="texthidden" style="font-weight: bold">
                  {{ currentRow.goodsName }}
                </div>
                <div class="textTherr">
                  {{ currentRow.slogan }}
                </div>
              </div>
            </div>
            <span>当前库存 {{ currentRow.stockName }}</span>
          </div>
          <div v-if="Number(currentRow.goodsId) != 0" class="goodsText">
            更换后
          </div>
          <div style="margin-right: 40px">
            <el-link
              v-if="selectRow == ''"
              type="primary"
              style="font-size: 17px; font-weight: bold"
              @click="aggregateVisible = true"
              >请选择商品</el-link
            >
            <div v-else>
              <div class="goodsBox">
                <img
                  width="120px"
                  height="150px"
                  :src="selectRow.mainPicture"
                  alt=""
                />
                <div class="sloganaBox">
                  <div class="texthidden" style="font-weight: bold">
                    {{ selectRow.name }}
                  </div>
                  <div class="textTherr">
                    {{ selectRow.slogan }}
                  </div>
                </div>
              </div>
              <el-link type="primary" @click="aggregateVisible = true"
                >重新选择</el-link
              >
            </div>
          </div>
          <div v-if="Number(currentRow.goodsId) == 0"></div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="visible = false" size="small">取 消</el-button>
          <el-button
            type="primary"
            size="small"
            @click="onConfirm"
            :loading="confirmLoading"
            >{{ confirmLoading ? "提交中 ..." : "确 定" }}</el-button
          >
        </div>
      </el-dialog>

      <el-dialog
        append-to-body
        :visible.sync="aggregateVisible"
        width="60%"
        @close="closeChange"
      >
        <el-form :inline="true" label-width="110px" :model="comForm">
          <el-form-item label="商品名" prop="commodityName">
            <el-input
              maxlength="20"
              size="small"
              v-model="comForm.commodityName"
              placeholder="请输入内容"
              @clear="comSearch"
            ></el-input>
          </el-form-item>
          <el-form-item label-width="20px">
            <el-button type="primary" size="small" @click="comSearch"
              >搜索</el-button
            >
          </el-form-item>
        </el-form>
        <el-table ref="aggTable" :data="commodityTableData">
          <el-table-column label="商品图" prop="mainPicture">
            <template slot-scope="scope">
              <img
                :src="scope.row.mainPicture"
                width="50px"
                height="50px"
                alt=""
                srcset=""
              />
            </template>
          </el-table-column>
          <el-table-column
            label="商品名"
            :show-overflow-tooltip="tooltip"
            prop="name"
          ></el-table-column>
          <el-table-column
            label="商品类目"
            prop="goodsTypeName"
          ></el-table-column>
          <el-table-column label="售价" prop="sellingPrice"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" @click="aggregateClick(scope.row)"
                >选择</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            @size-change="comHandleSizeChange"
            @current-change="comHandleCurrentChange"
            :current-page="comPageNumber"
            :page-size="comPageSize"
            layout="total, prev, pager, next, jumper"
            :total="comTotal"
          ></el-pagination>
        </div>
      </el-dialog>

      <el-dialog
        append-to-body
        title="销售记录"
        :visible.sync="marketVisible"
        width="60%"
        @close="orderId = ''"
      >
        <el-table ref="marketTable" :data="marketTableData">
          <!-- <el-table-column label="商品图" prop="mainPicture">
            <template slot-scope="scope">
              <img
                :src="scope.row.mainPicture"
                width="50px"
                height="50px"
                alt=""
                srcset=""
              />
            </template>
          </el-table-column> -->
          <el-table-column label="订单号" prop="orderCode"></el-table-column>
          <el-table-column
            label="商品信息"
            :show-overflow-tooltip="tooltip"
            prop="slogan"
          ></el-table-column>
          <el-table-column label="购买人" prop="petName"></el-table-column>
          <el-table-column label="电话号码" prop="phone"></el-table-column>
          <el-table-column label="售价" prop="billAmount"></el-table-column>
          <el-table-column prop="stateName" label="支付状态"> </el-table-column>
        </el-table>
      </el-dialog>

      <el-dialog
        append-to-body
        title="批量设置商品"
        :visible.sync="gridVisible"
        @close="getData"
        width="70%"
      >
        <div class="gridContent">
          <div class="gridBox" v-for="(item, index) in gridData" :key="index">
            <div class="gridOne">
              <span>{{ item.gridCode }}</span>
              <el-link
                v-if="item.usageStatus == 1 && item.goodsId != 0"
                type="primary"
                @click="handleEdit(item, 'all', index)"
                >换货</el-link
              >
            </div>
            <div
              class="gridTwo"
              v-if="item.usageStatus == 1 && item.goodsId != 0"
            >
              <div class="texthidden" style="font-weight: bold">
                {{ item.goodsName }}
              </div>
              <div class="textTherr">
                {{ item.slogan }}
              </div>
            </div>
            <div
              class="gridPrice"
              v-if="item.usageStatus == 1 && item.goodsId != 0"
            >
              售价：<span>{{ item.sellingPrice }}元</span>
            </div>
            <div v-if="item.usageStatus == 2" class="gridThree">
              <span> 格口已经被禁用 </span>
              <el-link type="primary" @click="handleDel(item)">启用</el-link>
            </div>
            <div class="gridThree foreBox" v-if="item.goodsId == 0">
              <i
                @click="handleEdit(item, 'all', index)"
                class="el-icon-plus gridTextBlod"
              ></i>
              添加商品
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            size="small"
            @click="gridClick"
            :loading="confirmLoading"
            >{{ confirmLoading ? "提交中 ..." : "确 定" }}</el-button
          >
        </div>
      </el-dialog>

      <!-- 库存编辑 -->
      <el-dialog
        width="50% "
        :visible.sync="inventoryVisible"
        @close="inventoryClear"
        custom-class="custom_drawer"
      >
        <div class="flexRow" style="width: 80%">
          <span>设备ID：{{ lockerRow.deviceCode }}</span>
          <span>设备名字：{{ lockerRow.deviceName }}</span>
          <span>所属商户：{{ lockerRow.merchantName }}</span>
          <span>格口号：{{ currentRow.gridCode }}</span>
        </div>
        <div class="contentBox">
          <div v-if="Number(currentRow.goodsId) == 0"></div>
          <div v-if="Number(currentRow.goodsId) != 0">
            <div>当前商品</div>
            <div class="goodsBox">
              <img
                width="120px"
                height="150px"
                :src="currentRow.mainPicture"
                alt=""
              />
              <div class="sloganaBox">
                <div class="texthidden" style="font-weight: bold">
                  {{ currentRow.goodsName }}
                </div>
                <div class="textTherr">
                  {{ currentRow.slogan }}
                </div>
              </div>
            </div>
          </div>
          <div v-if="Number(currentRow.goodsId) == 0">
            当前格口未设置商品,请设置商品后修改库存
          </div>
          <div
            v-if="Number(currentRow.goodsId) != 0"
            style="margin-right: 40px"
          >
            <el-form
              :inline="true"
              ref="inventoryForm"
              label-width="90px"
              :model="inventoryForm"
            >
              <el-form-item
                :rules="{
                  required: true,
                  message: '不能为空',
                  trigger: 'change',
                }"
                label="库存数量"
                prop="inventory"
              >
                <el-input
                  oninput="this.value=this.value.replace(/[^\d]/g, '');"
                  size="small"
                  v-model="inventoryForm.inventory"
                  placeholder="库存最少为0，最多为1"
                  clearable
                ></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div v-if="Number(currentRow.goodsId) == 0"></div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="inventoryVisible = false" size="small"
            >取 消</el-button
          >
          <el-button
            v-if="Number(currentRow.goodsId) != 0"
            type="primary"
            size="small"
            @click="inventoryClick('inventoryForm')"
            :loading="confirmLoading"
            >{{ confirmLoading ? "提交中 ..." : "确 定" }}</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  gridList,
  editGridStatus,
  goodsSel,
  MAIN,
  deviceChange,
  orderList,
  goodsChangesAll,
  updateStock,
} from "../../utils/api";
import BackButton from "../../components/BackButton";
export default {
  name: "BoxList",
  props: ["height"],

  data() {
    return {
      comForm: {
        commodityName: "",
      },
      gridVisible: false,
      selectRow: "",
      commodityTableData: [],
      aggregateVisible: false,
      marketVisible: false,
      marketTableData: [],
      comTotal: 0,
      comPageNumber: 1,
      comPageSize: 6,
      tableData: [],
      locker_id: "", //路由传值 菜品id
      merchant_id: "", //路由传值 商家id
      tooltip: true, //内容过长被隐藏时显示 tooltip
      loading: true, //显示加载表格
      pageSize: 10, //每页多少条
      currentPage: 1, //当前第几页
      pageSizes: [10, 20, 30, 40, 50], //每页选择条数
      total: 0, //共多少条
      errImg: 'this.src="' + require("../../../static/img/user.png") + '"',
      permission: {
        add: false,
        edit: false,
        del: false,
        gridDel: false,
        goodsSet: false,
      }, //权限
      //编辑弹窗
      orderPageNumber: 1,
      orderPageSize: 6,
      orderTotal: 0,
      visible: false,
      confirmLoading: false,
      type: "",
      currentRow: {}, //当前行数据信息
      ruleForm: {
        name_box: "",
        name_line: "",
        remark: "",
        locker_box_size_id: "",
        is_enabled: "",
        is_used: "",
      }, //添加和修改的表单
      userInfo: {},
      rules: {
        locker_box_size_id: [
          { required: true, message: "请选择格口大小", trigger: "change" },
        ],
        is_enabled: [
          { required: true, message: "请选择是否可用", trigger: "change" },
        ],
        is_used: [
          { required: true, message: "请选择是否启用", trigger: "change" },
        ],
        name_box: [
          { required: true, message: "请输入格口号", trigger: "blur" },
        ],
        name_line: [
          { required: true, message: "请输入线路号", trigger: "blur" },
        ],
        remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
      },
      size: {}, //尺寸的下拉列表
      lockerRow: {},
      orderId: "", //订单id
      gridData: [],
      gridType: "",
      gridIndex: "",
      inventoryVisible: false,
      inventoryForm: {
        inventory: "",
      },
    };
  },
  components: {
    BackButton,
  },

  // destroyed() {
  //   window.sessionStorage.removeItem("lockerRow");
  // },
  created() {
    this.lockerRow = JSON.parse(window.sessionStorage.getItem("lockerRow"));
    this.getCommodity();
  },

  mounted() {
    this.getResource();
  },
  methods: {
    inventoryClear() {
      this.$refs.inventoryForm.resetFields();
    },
    // 库存编辑保存
    inventoryClick(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          let params = {
            userId: this.userInfo.id,
            id: this.currentRow.id,
            number: this.inventoryForm.inventory,
          };
          this.postRequest(updateStock, params, MAIN).then((res) => {
            this.confirmLoading = false;

            if (res.code === 200) {
              this.inventoryVisible = false;
              this.$notify.success(res.msg);
              this.getData();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 批量设置保存
    gridClick() {
      let params = {
        userId: this.userInfo.id,
        deviceId: this.lockerRow.id,
        grids: this.gridData,
      };
      this.confirmLoading = true;
      // console.log(params);
      this.postRequest(goodsChangesAll, params, MAIN).then((res) => {
        this.confirmLoading = false;

        if (res.code === 200) {
          this.$notify.success(res.msg);
          this.gridVisible = false;
          this.getData();
        }
      });
    },
    aggregateClick(row) {
      this.selectRow = row;
      this.aggregateVisible = false;
    },
    // 选择商品弹框关闭
    closeChange() {},
    // 适用商品搜索
    comSearch() {
      this.comPageNumber = 1;
      this.getCommodity();
    },
    //分页
    comHandleSizeChange(val) {
      //每页 ${val} 条
      this.comPageSize = val;
      this.getCommodity();
    },
    comHandleCurrentChange(val) {
      //当前页
      this.comPageNumber = val;
      this.getCommodity();
    },

    // 销售记录分页
    orderHandleSizeChange(val) {
      //每页 ${val} 条
      this.orderPageSize = val;
      this.getorderList(this.orderId);
    },
    // 销售记录分页
    orderHandleCurrentChange(val) {
      //当前页
      this.orderPageNumber = val;
      this.getorderList(this.orderId);
    },
    // 获取销售记录
    getorderList(id) {
      this.orderId = id;
      let params = {
        deviceGridId: id,
        pageSize: this.orderPageSize,
        pageNumber: this.orderPageNumber,
      };
      this.postRequest(orderList, params, MAIN).then((res) => {
        if (res.code === 200) {
          this.marketTableData = res.data.list;
          this.orderTotal = res.data.count;
          this.marketVisible = true;
        }
      });
    },
    // 获取适用商品
    getCommodity() {
      let params = {
        name: this.comForm.commodityName,
        pageNumber: this.comPageNumber,
        pageSize: this.comPageSize,
        couponId: "",
      };
      this.postRequest(goodsSel, params, MAIN).then((res) => {
        if (res.code == 200) {
          this.commodityTableData = res.data.list;
          this.comTotal = res.data.count;
          this.$nextTick(() => {
            //避免表格表头样式错乱
            if (this.$refs.aggTable) this.$refs.aggTable.doLayout();
          });
        }
      });
    },
    getResource() {
      // console.log(this.$route.name);
      this.loading = true;
      const userinfo = JSON.parse(sessionStorage.getItem("userInfo")); //解密,获取用户登录信息
      this.userInfo = userinfo;
      let arr = userinfo.menu_id.split(",");
      // console.log(arr)
      // 库存编辑 60
      // 商品编辑 56
      // gridDel, // 格口禁用  101
      // goodsSet 、// 批量设置 62
      if (arr.indexOf("60") > -1) {
        this.permission.add = true;
      }
      if (arr.indexOf("56") > -1) {
        this.permission.edit = true;
      }

      if (arr.indexOf("101") > -1) {
        this.permission.gridDel = true;
      }
      if (arr.indexOf("62") > -1) {
        this.permission.goodsSet = true;
      }

      this.getData();
      // this.sizeSelects();
    },

    //获取初始数据
    getData() {
      this.loading = true;
      let params = {
        deviceId: this.lockerRow.id,
        // pageNumber: this.currentPage,
        // pageSize: this.pageSize,
      };
      this.postRequest(gridList, params, MAIN).then((res) => {
        if (res.code == 200) {
          //   console.log(res);
          this.tableData = res.data.grids;
          this.gridData = res.data.grids;
          this.loading = false;

          // this.total = res.data.count;
          this.$nextTick(() => {
            //避免表格表头样式错乱
            if (this.$refs.table) this.$refs.table.doLayout();
          });
        }
      });
    },

    //分页
    handleSizeChange(val) {
      //每页 ${val} 条
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      //当前页
      this.currentPage = val;
      this.getData();
    },
    //新增
    handleAdd() {
      this.currentRow = {};
      this.gridVisible = true;
    },
    //编辑
    handleEdit(row, type, index) {
      this.gridType = type;
      this.currentRow = row;
      this.visible = true;
      if (type == "all") {
        this.gridIndex = index;
      }
      // console.log(this.selectRow);
    },
    // 库存编辑
    inventoryEdit(row) {
      this.inventoryVisible = true;
      this.currentRow = row;
    },
    //删除
    handleDel(row) {
      let parm = {
        id: row.id,
        userId: this.userInfo.id,
        usageStatus: row.usageStatus == 1 ? 2 : 1,
      };
      this.$confirm("确认修改?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.postRequest(editGridStatus, parm, MAIN).then((res) => {
            // console.log(res);
            if (res.code == 200) {
              this.$notify({
                title: "修改成功",
                message: res.msg,
                type: "success",
              });
              this.getData();
            }
          });
        })
        .catch(() => {});
    },

    onConfirm() {
      console.log(this.currentRow);
      if (this.gridType == "one") {
        let params = {
          id: this.currentRow.id,
          goodsId: this.selectRow.id,
          userId: this.userInfo.id,
        };
        this.postRequest(deviceChange, params, MAIN).then((res) => {
          if (res.code === 200) {
            this.$notify.success(res.msg);
            this.getData();
            this.visible = false;
          }
        });
      } else if (this.gridType == "all") {
        this.gridData[this.gridIndex].goodsId = this.selectRow.id;
        this.gridData[this.gridIndex].mainPicture = this.selectRow.mainPicture;
        this.gridData[this.gridIndex].goodsName = this.selectRow.name;
        this.gridData[
          this.gridIndex
        ].sellingPrice = this.selectRow.sellingPrice;
        this.gridData[this.gridIndex].slogan = this.selectRow.slogan;

        this.visible = false;
      }
    },

    onCancel() {
      this.selectRow = "";
      // this.$refs[formName].resetFields();
    },
  },
};
</script>

<style scoped>
/deep/ .el-input-group__append,
.el-input-group__prepend {
  background-color: #1890ff;
  color: #fff;
  cursor: pointer;
}
/deep/ .el-input--mini .el-input__inner {
  height: 32px;
  line-height: 32px;
}

/deep/ input::-webkit-outer-spin-button,
/deep/ input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
/deep/ input[type="number"] {
  -moz-appearance: textfield;
}
.flexRow {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.sloganaBox {
  width: 105px;
  line-height: 25px;
  margin-left: 20px;
}

.textBlod {
  font-weight: bold;
  font-size: 18px;
}
.contentBox {
  padding: 10px 40px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 200px;
}
.goodsText {
  font-size: 20px;
  font-weight: bold;
}
.goodsBox {
  display: flex;
  align-items: center;
  margin: 20px 0px;
}
.gridContent {
  display: flex;
  flex-wrap: wrap;
  margin-left: 30px;
}
.gridBox {
  border: 1px solid gray;
  width: 24%;
  height: 200px;
  padding: 20px;
  box-sizing: border-box;
}
.gridOne {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
.gridOne span {
  font-weight: bold;
  font-size: 18px;
}
.gridTwo {
  line-height: 21px;
}
.gridThree {
  display: flex;
  flex-direction: column;
  align-items: center;
  line-height: 25px;
  margin-top: 50px;
}
.gridTextBlod {
  font-size: 70px;
  font-weight: bold;
}
.foreBox {
  margin-top: 20px;
  line-height: 30px;
}
.gridPrice {
  margin-top: 20px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.gridPrice span {
  color: red;
  font-size: 17px;
}
.flexRow span {
  width: 25%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.texthidden {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2; /*想省略几行就写几*/
  -webkit-box-orient: vertical;
}
.textTherr {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3; /*想省略几行就写几*/
  -webkit-box-orient: vertical;
}
</style>
